package com.xb.chain.netty.client;

import com.xb.chain.constant.InfoConstant;
import com.xb.chain.entity.ConnectionInfo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author xiaobin
 * @date 2020/2/22 19:13
 * @desc node客户端连接
 */
@Slf4j
public class NodeClientStart {

    private static ExecutorService executorService = Executors.newFixedThreadPool(InfoConstant.THREAD_POOL_SIZE);

    public static void serverConnection(String ip, Integer port)  {
        executorService.execute(()->{
            NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(1);

            try {
                Bootstrap bootstrap = new Bootstrap().group(eventLoopGroup).channel(NioSocketChannel.class).handler(new NodeClientInit());
                ChannelFuture sync = bootstrap.connect(ip, port).sync();
                Channel channel = sync.channel();
                ConnectionInfo connectionInfo = ConnectionInfo.builder().ip(ip).port(port).build();
                InfoConstant.clientChannelGroup.put(connectionInfo,channel);
                log.info("连接新节点---ip:{},port:{}",ip,port);
                sync.channel().closeFuture().sync();
            } catch (Exception e) {
                log.error("客户端连接异常：检查节点 ip:{},port:{}是否启动",ip,port);
            } finally {
                eventLoopGroup.shutdownGracefully();
            }
        });
    }



//    public static void main(String[] args) throws Exception {
//        NodeClientStart.serverConnection("127.0.0.1", 9999);
//    }

}
